package ch.christianschweizer.epk.common.view.util;

import java.util.List;
import java.util.Map;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;

import oracle.binding.AttributeBinding;
import oracle.binding.OperationBinding;


public class ADFUtil {

    public static DCBindingContainer getBindings() {
        DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        if (bindings == null) {
            throw new IllegalStateException("BindingContainer missing");
        }
        return bindings;
    }

    public static void executeOperation(String name, Map<String, String> parameters) {
        OperationBinding operation = getBindings().getOperationBinding(name);
        if (operation != null) {
            if (parameters != null) {
                operation.getParamsMap().putAll(parameters);
            }
            operation.execute();

            // Fehlerbehandlung
            List errors = operation.getErrors();
            if (!errors.isEmpty()) {
                Exception e = (Exception)errors.get(0);
                ADFUtil.getBindings().reportException(e);
            }
        }
    }

    public static <T> T getBindingAttribute(String name, Class<T> type) {
        AttributeBinding attribute = (AttributeBinding)getBindings().getControlBinding(name);
        if (attribute == null) {
            throw new IllegalStateException("Attribute missing: " + name);
        }
        return type.cast(attribute.getInputValue());
    }

    public static void setBindingAttribute(String name, Object value) {
        AttributeBinding attribute = (AttributeBinding)getBindings().getControlBinding(name);
        if (attribute == null) {
            throw new IllegalStateException("Attribute missing: " + name);
        }
        attribute.setInputValue(value);
    }

}
